package javafx.webview.demo;

import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.web.WebErrorEvent;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.webview.demo.service.EatService;
import javafx.webview.demo.service.FruitsService;
import javafx.webview.demo.utils.Java2JavascriptUtils;
import javafx.webview.demo.service.CalculatorService;

public class WebViewDemo extends Application {
	
	/**
	 * 加载默认的页面
	 */
	private final String PAGE = "/index.html";

	@Override
	public void start(Stage primaryStage) {
		createWebView(primaryStage, PAGE);
	}

	private void createWebView(Stage primaryStage, String page) {
		
		//创建一个webView
		final WebView webView = new WebView();
		webView.getEngine().setOnError(new EventHandler<WebErrorEvent>() {
			@Override
			public void handle(WebErrorEvent event) {
				event.getException().printStackTrace();
                String message = event.getMessage();
                System.out.println(message);
            }
		});

        //注册一个服务到javascript中，把相应的名字，与相应的java实例绑定，调用javascritp方法会调用java代码
		Java2JavascriptUtils.connectBackendObject(
				webView.getEngine(),
				"eatService", new EatService());

		//注册一个服务到javascript中，把相应的名字，与相应的java实例绑定，调用javascritp方法会调用java代码
		Java2JavascriptUtils.connectBackendObject(
				webView.getEngine(),
				"fruitsService", new FruitsService());
		
		//注册一个服务到javascript中，把相应的名字，与相应的java实例绑定，调用javascritp方法会调用java代码
		Java2JavascriptUtils.connectBackendObject(
				webView.getEngine(),
				"calculatorService", new CalculatorService());
		
		//显示alert的处理
		webView.getEngine().setOnAlert(new EventHandler<WebEvent<String>>(){
			@Override
			public void handle(WebEvent<String> arg0) {
				System.err.println("alertwb1: " + arg0.getData());
			}
		});
		
		//加载index.html
		webView.getEngine().load(getClass().getResource(page).toExternalForm());

		primaryStage.setScene(new Scene(webView));
		primaryStage.setTitle("java");		
		primaryStage.show();
	}
	
	public static void main(String[] args) {		
		System.setProperty("prism.lcdtext", "false"); // enhance fonts		
		launch(args);
	}
}
